<template>
  <div>
    <div id="container" class="amap-wrapper">
      <info-window ref='infoWindow' @clickshow="showInfo" @closeInfoWindow="closeInfoWindow" :info="info"></info-window>
      <el-button round class="input-card" @click="onClickdefault">{{ israngingTool ? '關閉' : '開啟' }}測距</el-button>
      <span v-if="changeAssets.address" id="mapdreess" class="map-address dn" :title="changeAssets.address"
        style="overflow: hidden; display: inline;">{{ changeAssets.address }}</span>
      <span class="timer"><span class="green">{{ countdown }}</span>秒後刷新</span>
    </div>
  </div>
</template>

<script>
  import InfoWindow from './info-window'
  import MapLoader from '@/assets/js/AMap.js'
  import {
    mapState
  } from 'vuex'

  export default {
    name: 'map-container',

    components: {
      [InfoWindow.name]: InfoWindow
    },

    props: {
      copyCountdown: {
        type: Number,
        default: () => 20,
        required: false
      }
    },

    data() {
      return {
        info: '',
        infoBaseWindow: null,
        infoWindow: null,
        ruler: null,
        israngingTool: false,
        countdown: 20,
        marker: null,
        coordinate: []
      }
    },

    computed: {
      ...mapState({
        assetsMapLists: (state) => state.map.assetsMapLists,
        changeAssets: (state) => state.map.changeAssets,
        showName: (state) => state.map.showName,
        assetsDetails: (state) => state.map.assetsDetails
      })
    },

    mounted() {

      MapLoader().then(AMap => {
        setTimeout(() => {
          this.createAmap() //加载地图
          this.countDown() //开启倒计时刷新
        }, 500)
      }, e => {
        console.log('地图加载失败', e)
      })
    },

    methods: {

      createAmap() {
        var map = new AMap.Map("container", {
          // center: [22.277468, 114.171203],
          zoom: 11,
          resizeEnable: true,
          viewMode: '2D',
          lang: 'zh_cn'
        }) //初始化地图

        let scale = new AMap.Scale({
          visible: true
        })

        let toolBar = new AMap.ToolBar({
          visible: true
        })

        //自定义样式
        var startMarkerOptions = {
          icon: new AMap.Icon({
            size: new AMap.Size(19, 31), //图标大小
            imageSize: new AMap.Size(19, 31),
            image: require('@/assets/img/start.png')
          })
        }

        var endMarkerOptions = {
          icon: new AMap.Icon({
            size: new AMap.Size(19, 31), //图标大小
            imageSize: new AMap.Size(19, 31),
            image: require('@/assets/img/end.png')
          }),
          // offset: new AMap.Pixel(-9, -31)
        }

        var midMarkerOptions = {
          icon: new AMap.Icon({
            size: new AMap.Size(19, 31), //图标大小
            imageSize: new AMap.Size(19, 31),
            image: require('@/assets/img/mid.png')
          }),
          // offset: new AMap.Pixel(-9, -31)
        }

        var lineOptions = {
          strokeStyle: "solid",
          strokeColor: "#FF33FF",
          strokeOpacity: 1,
          strokeWeight: 2
        }

        var rulerOptions = {
          startMarkerOptions: startMarkerOptions,
          midMarkerOptions: midMarkerOptions,
          endMarkerOptions: endMarkerOptions,
          lineOptions: lineOptions
        }

        this.ruler = new AMap.RangingTool(map, rulerOptions);

        let mapType = new AMap.MapType({
          defalutType: 0,
          showTraffic: true,
          showRoad: true
        })

        //统一图标样式
        var icon = new AMap.Icon({
          image: require('@/assets/img/automobile-offline-0.png'),
          imageSize: new AMap.Size(48, 48)
        })

        //遍历生成多个标记点 因后端返回是map格式因此需要判断code
        this.coordinate = this.assetsMapLists //拿到数据
        let coordinate = this.assetsMapLists //定义coordinate
        for (let i = 0; i < this.coordinate.length; i++) {
          //信息窗口实例
          let infoWindow = new AMap.InfoWindow({
            isCustom: true, //是否自定义信息窗口（默认false，会有一个白框包裹）
            offset: new AMap.Pixel(15, -10), //偏移量
            position: [coordinate[i].longitude, coordinate[i].latitude], //弹出窗口的位置
            content: this.$refs.infoWindow.$el
          })

          //默认打开infoWindow
          // infoWindow.open(map)

          //设备名信息窗
          let infoBaseWindow = new AMap.InfoWindow({
            position: [coordinate[i].longitude, coordinate[i].latitude], //弹出窗口的位置
            content: this.changeAssets.facilityName,
            offset: new AMap.Pixel(15, -10), //偏移量
          })

          if (this.showName) { //设备名是否显示
            infoBaseWindow.open(map)
          }

          //几个点就给几个marker
          let marker = new AMap.Marker({
            map: map,
            // visible: false,
            position: new AMap.LngLat(coordinate[i].longitude, coordinate[i].latitude), //不同标记点的经纬度
            icon: icon
          })
          marker.on("click", markerClick);
          marker.emit("click", {
            target: marker
          }); //默认初始化不出现信息窗体,打开初始化就出现信息窗体

          // marker.on('moving', function(e) {
          //   passedPolyline.setPath(e.passedPath)
          // })

          function markerClick(e) {
            infoWindow.open(map, e.target.getPosition())
            // infoWindow.setContent(e.target.content)//不要解开
          }
        }

        map.setFitView()
        map.addControl(scale)
        map.addControl(toolBar)
        map.addControl(mapType)
      },

      showInfo(info) {
        console.log(1, info)
      },

      openInfoWindow() {
        this.infoWindow.open(this.map)
      },

      closeInfoWindow() {
        //关闭信息窗口
        this.infoWindow.close()
      },

      onClickdefault() {
        if (!this.israngingTool) {
          this.ruler.turnOn();
        } else {
          this.ruler.turnOff();
        }
        this.israngingTool = !this.israngingTool
      },

      countDown() {
        var i = this.copyCountdown
        this.countdown = this.copyCountdown
        const updateTime = () => {
          if (i == 0) {
            i = this.copyCountdown
            this.countdown = this.copyCountdown
          }
          i--
          this.countdown--
        }
        setInterval(updateTime, 1000)
      },

      //刷新地图
      resetMap() {
        // this.createAmap()
        // console.log('刷新地图')
      }
    }
  }
</script>

<style scoped lang="scss">
  @import "../../../assets/css/them.scss";

  /* 设置地图容器的长和宽,必不可少 */
  .amap-wrapper {
    min-width: 1000px;
    width: 100%;
    height: calc(100vh - 200px);
    min-height: 600px;
  }

  .input-card {
    position: fixed;
    right: 30px;
    z-index: 999;
    top: 350px;
  }

  /deep/ .amap-toolbar,
  /deep/ .amap-scalecontrol,
  /deep/ .amap-maptypecontrol,
  .input-card,
  /deep/ .amap-geolocation-con {
    z-index: 9 !important;
  }

  .map-address {
    left: 286px;
    right: 260px;
    top: 0px;
    padding: 8px 15px;
    border-top: 0;
    border-radius: 0 0 50px 50px;
    background-color: #fff;
    font-size: 14px;
    color: #000;
    font-weight: 500;
    text-align: center;
    position: absolute;
    z-index: 20;
    border: 1px solid rgba(0, 0, 0, .15);
    box-shadow: 0px 1px 4px -1px #eee
  }

  .timer {
    position: absolute;
    top: 10px;
    left: 100px;
    z-index: 20;
    background-color: rgba(255, 255, 255, .9);
    padding: 4px 8px;
    border: 1px solid rgba(0, 0, 0, .15);
    border-radius: 4px;
    box-shadow: 0px 1px 4px -1px #EEEEEE;

    .green {
      color: #4EAD5B;
      margin-right: 5px;
    }
  }

  /deep/ .amap-info-close {
    display: none;
  }

  /deep/ .amap-info-content {
    background-color: rgba(219, 53, 53, .9);
    border-color: #af2a2a;
    color: #fff;
  }

  /deep/ .bottom-center .amap-info-sharp {
    border-top: 10px solid #af2a2a;
  }
</style>
